package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

//分类模块
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    //新增分类
    @Override
    public void save(Category category) {
        //1补全信息
        long id = IdUtil.createSnowflake(1, 1).nextId();
       // category.setId(id);
       // category.setCreateTime(new Date());
       // category.setUpdateTime(new Date());
       // category.setCreateUser(1L);
       // category.setUpdateUser(1l);
//调用mapper添加
        categoryMapper.save(category);
    }

    // 修改分类
    @Override
    public void updateById(Category category) {
       // // 1.补全信息
       // category.setUpdateUser(1L); // todo 后期完善
       // category.setUpdateTime(new Date());
       // // 2.调用mapper修改
        categoryMapper.updateById(category);
    }
    //删除分类
    @Override
    public void deleteById(long id) {
        // 1.根据分类id查询菜品数量，判断
        Long countDish = categoryMapper.countDishByCategoryId(id);
        if (countDish > 0) {
            throw new CustomException("该分类下有菜品，删除失败");
        }
        // 2.根据分类id查询套餐数量，判断
        Long countSetmeal = categoryMapper.countSetmealByCategoryId(id);
        if (countSetmeal > 0) {
            throw new CustomException("该分类下有套餐，删除失败");
        }
        // 3.根据id删除分类
        categoryMapper.deleteById(id);
    }

    @Override
    public List<Category> findByType(Integer type) {
        //构建条件
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.eq(Category::getType,type);//类型条件
        qw.orderByAsc(Category::getSort);//排序
        //调用mapper查询并且返回
        return categoryMapper.selectList(qw);
    }

    //删除分类
   //@Override
   //public ResultInfo delelteById(long id) {
   //    // 1.根据分类id查询菜品数量，判断
   //    long countDish = categoryMapper.countDishByCategoryId(id);
   //    if (countDish > 0) {
   //        return ResultInfo.error("该分类下有菜品不允许删除");
   //    }
   //    //2根据分类id查询套餐数量
   //    long countSetmeal=categoryMapper.countSetmealByCategoryId(id);
   //    if (countSetmeal > 0) {
   //        return ResultInfo.error("该分类下有套餐不允许删除");
   //    }
   //    categoryMapper.deleteById(id);
   //    return ResultInfo.success();
   //}
}
